package com.sprite.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 *
 * @author Jack
 */
public final class UtilDateTime {
    private static Map<String, SimpleDateFormat> dateFormats = new HashMap<>();

    /**
     * 格式化显示
     *
     * @param date
     *         日期
     * @param pattern
     *         格式
     * @return 格式化显示
     */
    public static String toDateString(Date date, String pattern) {
        SimpleDateFormat format = dateFormats.get(pattern);

        if (format == null) {
            format = new SimpleDateFormat(pattern);
            dateFormats.put(pattern, format);
        }

        return format.format(date);
    }

    public static Long getTime(Date date) {
        if (date != null) {
            return date.getTime();
        }

        return null;
    }

    public static Date nowDate() {
        return new Date();
    }

    public static String nowDateString(String pattern) {
        return toDateString(new Date(), pattern);
    }

    public static Date toDate(int year, int month, int day, int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();

        try {
            calendar.set(year, month - 1, day, hour, minute, second);
            calendar.set(Calendar.MILLISECOND, 0);
        } catch (Exception e) {
            return null;
        }
        return new java.util.Date(calendar.getTime().getTime());
    }

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            System.out.println(format.parse("2015-9-30"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
